package auth

import (
	"douhu_backend/internal/controller/common"
	"douhu_backend/internal/errors"
	"douhu_backend/internal/log"
	"fmt"

	"github.com/kataras/iris/v12"
)

// Base 认证控制器基类
type Base struct {
}

// mapServiceError 将 Service 层错误映射到 Controller 层错误
func (b *Base) mapServiceError(serviceErr *errors.ServiceError) *Errno {
	switch serviceErr.Code {
	case errors.CodePhoneFormat:
		return ErrPhoneFormat
	case errors.CodeTypeInvalid:
		return ErrCodeType
	case errors.CodeInvalid:
		return ErrCodeInvalid
	case errors.CodeExpired:
		return ErrCodeExpired
	case errors.CodeSendTooFrequent:
		return ErrSendTooFrequent
	case errors.CodeDailyLimitExceed:
		return ErrDailyLimitExceeded
	case errors.CodeSMSSendFailed:
		return ErrSMSSendFailed
	case errors.CodeUserNotFound:
		return ErrUserNotFound
	case errors.CodeUserDisabled:
		return ErrUserDisabled
	case errors.CodeLoginLocked:
		return ErrLoginLocked
	case errors.CodeTokenInvalid:
		return ErrTokenInvalid
	case errors.CodeTokenExpired, errors.CodeTokenRevoked:
		return ErrTokenExpired
	case errors.CodeCreateUserFailed:
		return ErrCreateUserFailed
	case errors.CodeUpdateUserFailed:
		return ErrUpdateUserFailed
	case errors.CodeSaveSMSCodeFailed:
		return ErrSaveSMSCodeFailed
	case errors.CodeUserAlreadyExists:
		return ErrUserAlreadyExists
	default:
		return ErrSystemError
	}
}

// Error 返回失败响应
func (b *Base) Error(ctx iris.Context, code int, message string, err error) {
	logMsg := message

	if err != nil {
		logMsg += fmt.Sprintf(" error:%s", err.Error())
	}

	log.Errorf(logMsg)
	ctx.JSON(common.RspProto{
		Code:      code,
		Message:   message,
		Data:      nil,
		Error:     logMsg,
		RequestID: ctx.Request().Header.Get("X-Request-Id"),
	})
}

// ErrorWithLog 返回失败响应（带日志信息）
func (b *Base) ErrorWithLog(ctx iris.Context, code int, message string, err error, logStr string) {
	logMsg := message

	if err != nil {
		logMsg += fmt.Sprintf(" error:%s", err.Error())
	}

	log.Errorf(logMsg)
	ctx.JSON(common.RspProto{
		Code:      code,
		Message:   message,
		Data:      logStr,
		Error:     logMsg,
		RequestID: ctx.Request().Header.Get("X-Request-Id"),
	})
}

// Success 返回成功响应
func (b *Base) Success(ctx iris.Context, data interface{}) {
	if data == nil {
		data = []int{}
	}
	ctx.JSON(common.RspProto{
		Code:      OK.Code,
		Message:   OK.Message,
		Data:      data,
		Error:     "",
		RequestID: ctx.Request().Header.Get("X-Request-Id"),
	})
}

// GetClientIP 获取客户端IP
func (b *Base) GetClientIP(ctx iris.Context) string {
	// 优先从X-Forwarded-For获取
	ip := ctx.Request().Header.Get("X-Forwarded-For")
	if ip != "" {
		return ip
	}

	// 从X-Real-IP获取
	ip = ctx.Request().Header.Get("X-Real-IP")
	if ip != "" {
		return ip
	}

	// 最后从RemoteAddr获取
	return ctx.RemoteAddr()
}
